package run.siyuan.jdk.漫画算法.栈;

import run.siyuan.jdk.漫画算法.链表.LinkedInsertDemo;
import run.siyuan.jdk.漫画算法.队列.LinkedQueue;

import javax.management.RuntimeMBeanException;

/**
 * @ClassName LinkedStack
 * @Description TODO 链表实现栈的入栈、出栈
 * @Author siyuan
 * @Date 2023/4/8 11:36
 */
public class LinkedStack {

    /**
     * 栈底/链表的头结点
     */
    private Node stackBottom = new Node();
    /**
     * 栈顶/链表的尾节点
     */
    private Node stackTop = new Node();
    /**
     * 以入栈的元素数量
     */
    private int size;


    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack();
        stack.pushStack(0);
        stack.pushStack(1);
        stack.pushStack(2);
        stack.pushStack(3);
        stack.pushStack(4);
        stack.show();

        stack.popStack();
        stack.popStack();

        stack.pushStack(5);
        stack.show();
    }

    /**
     * 入栈
     *
     * @param element
     */
    public void pushStack(int element) {
        Node insertNode = new Node(element);
        if (size == 0) {
            stackBottom.next = insertNode;
            stackTop.next = insertNode;

            insertNode.pre = stackBottom;
        } else if (size > 0) {
            Node node = stackTop.next;
            node.next = insertNode;

            insertNode.pre = node;
            stackTop.next = insertNode;
        }

        size++;

    }

    /**
     * 出栈
     */
    public void popStack() {
        if (size <= 0) {
            throw new RuntimeException("空栈");
        }
        Node node = stackTop.next;
        stackTop.next = node.pre;
        size--;
    }

    public void show() {
        Node node = stackBottom.next;
        for (int i = 0; i < size; i++) {
            System.out.printf("%d\t%d\n", i, node.data);
            node = node.next;
        }
    }


    class Node {
        private Node pre;
        private int data;
        private Node next;

        public Node() {
        }

        public Node(Node pre, int data, Node next) {
            this.pre = pre;
            this.data = data;
            this.next = next;
        }

        public Node(int data) {
            this.data = data;
        }

        public Node(Node pre, int data) {
            this.pre = pre;
            this.data = data;
        }
    }

}
